#include "stdio.h"
#include "motor.cpp"

int main()
{
	MouseDelta mickey, mini;
	int i, diffX, diffY;


	FILE *fmouse1;
	FILE *fmouse2;
	fmouse1 = fopen("/dev/input/mouse1","r");
	fmouse2 = fopen("/dev/input/mouse2","r");
	/*
	while(1)
	{
		getMouse(fmouse1);
		getMouse(fmouse2);
	}
*/
	int buffer1[WINDOW][2];
	int buffer2[WINDOW][2];
	bool reset = false;
	while(1)
	{
		mickey = getMouse(fmouse1);
		mini = getMouse(fmouse2);
		//printf("xd=%d, yd=%d\n", mickey.dx, mickey.dy);
		buffer1[0][0] = mickey.dx;
		buffer1[0][1] = mickey.dy;
		buffer2[0][0] = mini.dx;
		buffer2[0][1] = mini.dy;
		diffX = 0;
		diffY = 0;

		for(i = 0; i < WINDOW-1; i++)
		{
			diffX += (buffer1[i][0] - buffer2[i][0]);
			diffY += (buffer1[i][1] - buffer2[i][0]);
			buffer[i+1][0] = buffer[i][0];
			buffer[i+1][1] = buffer[i][1];
			buffer1[0][0] = 0;
			buffer1[0][1] = 0;
			buffer2[0][0] = 0;
			buffer2[0][1] = 0;
			
			if(diffX >= TRESHOLD)
			{
				goRight(0x50, 1);
				reset = true;
				sleep(1);
				stop();
			}
			else if(diffX <= -TRESHOLD)
			{
				goLeft(0x50, 1);
				reset = true;
				sleep(1);
				stop();
			}
			else if(diffY >= TRESHOLD)
			{
				goForward(0x50);
				sleep(2);
				stop();
				reset = true;
			}
			else if(diffY <= -TRESHOLD)
			{
				goBackward(0x30);
				sleep(2);
				stop();
				reset = true;
			}
			if(reset == true)
			{
				for(i = 0; i < WINDOW; i++)
				{
					buffer1[i][0] = 0;
					buffer1[i][1] = 0;
					buffer2[i][0] = 0;
					buffer2[i][1] = 0;
				}
				reset = false;
				sumX = 0;
				sumY = 0;
				//getMouse(fmouse);
				//getMouse(fmouse);
			}
			
		}
	}
	
	fclose(fmouse1);
	fclose(fmouse2);

	Drive(100);
	sleep(2);
	Drive(0);
	Rotate(45, true);
	return 0;
}
